package com.sojson.project.sys.log.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.sojson.enums.core.EStatusLogin;
import com.sojson.project.sys.log.entity.po.LogLogin;
import com.sojson.project.sys.log.entity.po.LogOper;
import com.sojson.project.sys.log.service.ISysLogService;
import com.sojson.project.sys.log.service.LogLoginService;
import com.sojson.project.sys.log.service.LogOperService;
import com.sojson.util.StringUtil;
import com.sojson.util.SystemParamBaseUtil;
import com.sojson.util.agent.UserAgentUtil;
import com.sojson.util.servlet.ServletUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统日志Service实现类
 * 
 * @author liu
 * @date 2021-11-09
 */
@Slf4j
@Service
public class LogServiceImpl implements ISysLogService {

    @Autowired
    LogLoginService loginService;
    @Autowired
    LogOperService operService;

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    @Async
    @Override
    public void recordLogininfor(final String username, final EStatusLogin status, final String message,
        final Object... args) {
        HttpServletRequest request = ServletUtil.getHttpServletRequest();
        UserAgentUtil.Agent userAgent = UserAgentUtil.getAccountAgent();
        final String ip = ServletUtil.getTargetIp(request);
        String address = getRealAddressByIp(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(username));
        s.append(getBlock(status));
        s.append(getBlock(message));
        // 打印信息到日志
        log.info(s.toString(), args);
        // 获取客户端操作系统
        String os = userAgent.getOs();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser();
        // 封装对象
        LogLogin logLogin = new LogLogin();
        logLogin.insertInit();
        logLogin.setUsername(username);
        logLogin.setIpaddr(ip);
        logLogin.setLoginLocation(address);
        logLogin.setBrowser(browser);
        logLogin.setOs(os);
        logLogin.setMsg(message);
        // 日志状态
        if (EStatusLogin.SUCCESS.equals(status) || EStatusLogin.LOGOUT.equals(status)) {
            logLogin.setStatus(EStatusLogin.SUCCESS.getCode());
        } else if (EStatusLogin.FAIL.equals(status)) {
            logLogin.setStatus(EStatusLogin.FAIL.getCode());
        }
        // 插入数据
        loginService.save(logLogin);
    }

    /**
     * 操作日志记录
     *
     * @param logOper 操作日志信息
     * @return 任务task
     */
    @Async
    @Override
    public void recordOper(final LogOper logOper) {
        logOper.insertInit();
        // 远程查询操作地点
        logOper.setOperLocation(getRealAddressByIp(logOper.getOperIp()));
        operService.save(logOper);
    }

    String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }

    /**
     * 获取目标IP的地理位置
     * 
     * @param ip
     * @return
     * @throws Exception 
     */
    String getRealAddressByIp(String ip) {
        // 内网不查询
        if (ServletUtil.internalIp(ip)) {
            return "内网IP";
        }

        try {
            // 系统日志是否查询所在地址
            Boolean isRealAddress = SystemParamBaseUtil.getBoolean("sys_log_is_real_address");
            if (StringUtil.isNotBlankObject(isRealAddress) && isRealAddress) {
                return ServletUtil.getRealAddressByIp(ip);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return ServletUtil.UNKNOWN;
    }

}